package com.ch.personmis.service;

import com.ch.personmis.entity.UserEntity;
import com.ch.personmis.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminRepository adminMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = adminMapper.getUserByUsername(username);

        // 检查用户是否存在
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名: " + username + " 不存在");
        }

        // 构建并返回Spring Security的UserDetails对象
        return User.builder()
                .username(userEntity.getUname())  // 用户名
                .password(userEntity.getUpwd())  // 密码
                .roles(userEntity.getRoles())  // 用户角色
                .build();
    }
}
